//
//  PHWiFiConnectViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2018/3/5.
//  Copyright © 2018年 Levy Xu. All rights reserved.
//

#import "PHWiFiConnectViewController.h"
#import "GizManager.h"
#import "PHAddUtils.h"

typedef enum : NSUInteger {
    WifiConnectStatusDefault,
    WifiConnectStatusConnecting,
    WifiConnectStatusConnected,
    WifiConnectStatusDisconnected,
    WifiConnectStatusSubscribing,
    WifiConnectStatusSubscribed,
    WifiConnectStatusUnsubscribed
} WifiConnectStatus;

@interface PHWiFiConnectViewController ()<GizWifiDeviceDelegate>
@property (strong, nonatomic) UIImageView *imageView1;
@property (strong, nonatomic) UIImageView *imageView2;
@property (strong, nonatomic) UILabel *proressLabel;
@property (strong, nonatomic) UILabel *wifiLabel;
@property (strong, nonatomic) UILabel *subscribeLabel;
@property(nonatomic, strong) QMUIFillButton *nextBtn;

@property (nonatomic, assign) WifiConnectStatus status;
@property (nonatomic, strong) KKTimer *timer;
@end

@implementation PHWiFiConnectViewController

- (void)initSubviews {
    [super initSubviews];
    
    _imageView1 = [[UIImageView alloc] initWithFrame:CGRectZero];
    _imageView1.backgroundColor = [UIColor clearColor];
    _imageView1.image = UIImageMake(@"wifi_connecting_in");
    [self.myView addSubview:_imageView1];
    
    _imageView2 = [[UIImageView alloc] initWithFrame:CGRectZero];
    _imageView2.backgroundColor = [UIColor clearColor];
    _imageView2.image = UIImageMake(@"wifi_connecting_out");
    [self.myView addSubview:_imageView2];
    
    _proressLabel = [[QMUILabel alloc] init];
    _proressLabel.font = CodeFontMake(40);
    _proressLabel.textColor = UIColorWhite;
    _proressLabel.textAlignment = NSTextAlignmentCenter;
    _proressLabel.text = @"0%";
    [_imageView1 addSubview:_proressLabel];
    
    _wifiLabel = [[QMUILabel alloc] init];
    _wifiLabel.font = CodeFontMake(15);
    _wifiLabel.textColor = UIColorGray3;
    _wifiLabel.textAlignment = NSTextAlignmentCenter;
    [self.myView addSubview:_wifiLabel];
    
    _subscribeLabel = [[QMUILabel alloc] init];
    [_subscribeLabel qmui_setTheSameAppearanceAsLabel:_wifiLabel];
    [self.myView addSubview:_subscribeLabel];
    
    _nextBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorRed];
    _nextBtn.titleLabel.font = CodeFontMake(16);
    [_nextBtn setTitle:NSLocalizedString(@"btn_retry", nil) forState:UIControlStateNormal];
    [_nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:_nextBtn];
}

- (void)viewDidLayoutSubviews {
    self.shouldShowMyView = YES;
    [super viewDidLayoutSubviews];
    
    _imageView1.frame = CGRectMake(self.myView.qmui_width / 2 - 100, 20, 200, 200);
    
    _imageView2.frame = _imageView1.frame;
    
    _proressLabel.frame = CGRectMake(0, _imageView1.qmui_height / 2 - 24, _imageView1.qmui_width, 48);
    
    _wifiLabel.frame = CGRectMake(30, _imageView2.qmui_bottom + 20, self.myView.qmui_width - 60, 20);
    _subscribeLabel.frame = CGRectMake(30, _wifiLabel.qmui_bottom + 5, self.myView.qmui_width - 60, 20);
    
    _nextBtn.frame = CGRectMake(30, _subscribeLabel.qmui_bottom + 20, self.myView.qmui_width - 60, 40);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

    [self startConnect];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

-(void)startConnect {
    self.status = WifiConnectStatusConnecting;
    
    WS(ws);
    [GGizManager wifiConnect:GPHAddUtils.ssid key:GPHAddUtils.key finishBlock:^(GizWifiDevice *device) {
        
        LOG(@"device %@",device);
        
        if (device) {
            ws.status = WifiConnectStatusConnected;
            
            if (device.isSubscribed) {
                ws.status = WifiConnectStatusSubscribed;
            } else {
                device.delegate = self;
                
                ws.status = WifiConnectStatusSubscribing;
                [device subscribe:YES];
            }
        } else {
            ws.status = WifiConnectStatusDisconnected;
        }
    }];
}

-(void)nextAction:(QMUIFillButton *)sender {
    if (_status == WifiConnectStatusSubscribed) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        [self startConnect];
    }
}

-(void)backAction:(id)sender {
    if (_status == WifiConnectStatusConnecting) {
        WS(ws);
        [KKAlert warningWithText:NSLocalizedString(@"tips_wifi_exit", nil) cancel:^{
            
        } ok:^{
            [GGizManager stopWifiConnect];
            [ws.navigationController popViewControllerAnimated:YES];
        }];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)setupNavigationItems {
    [super setupNavigationItems];
    self.title = NSLocalizedString(@"title_wifi_connect", nil);
}

-(void)setStatus:(WifiConnectStatus)status {
    _status = status;
    switch (status) {
        case WifiConnectStatusConnecting:
        {
            [self startAnimation];
            
            _nextBtn.hidden = YES;
            _wifiLabel.text = NSLocalizedString(@"tips_wifi_connecting", nil);
            _subscribeLabel.hidden = YES;
        }
            break;
        case WifiConnectStatusConnected:
        {
            _wifiLabel.text = NSLocalizedString(@"tips_wifi_success", nil);
        }
            break;
        case WifiConnectStatusDisconnected:
        {
            [self stopAnimation];
            
            _wifiLabel.text = NSLocalizedString(@"tips_wifi_failed", nil);
            _nextBtn.hidden = NO;
            [_nextBtn setTitle:NSLocalizedString(@"btn_retry", nil) forState:UIControlStateNormal];
        }
            break;
        case WifiConnectStatusSubscribing:
        {
            _subscribeLabel.hidden = NO;
            _subscribeLabel.text = NSLocalizedString(@"tips_binding", nil);
        }
            break;
        case WifiConnectStatusSubscribed:
        {
            [self stopAnimation];
            
            _subscribeLabel.text = NSLocalizedString(@"tips_bind_success", nil);
            _nextBtn.hidden = NO;
            [_nextBtn setTitle:NSLocalizedString(@"btn_ok", nil) forState:UIControlStateNormal];
        }
            break;
        case WifiConnectStatusUnsubscribed:
        {
            [self stopAnimation];
            
            _subscribeLabel.text = NSLocalizedString(@"tips_bind_failed", nil);
            _nextBtn.hidden = NO;
            [_nextBtn setTitle:NSLocalizedString(@"btn_retry", nil) forState:UIControlStateNormal];
        }
        default:
            break;
    }
}

-(void)startAnimation {
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.fromValue = @0.0;
    rotationAnimation.toValue = @(M_PI * 2.0);
    rotationAnimation.duration = 2.0;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = NSIntegerMax;
    [self.imageView2.layer addAnimation:rotationAnimation forKey:@"kRotationAnimation"];
    
    WS(ws);
    _timer = [KKTimer every:1.0f repeat:90 task:^(NSUInteger times) {
        float progress = times / (float)90;
        ws.proressLabel.text = [NSString stringWithFormat:@"%d%%", (int)(100 * progress)];
        if (times == 60 && ws.status == WifiConnectStatusConnecting) {
            self.status = WifiConnectStatusDisconnected;
        }
        else if (times == 90 && ws.status == WifiConnectStatusSubscribing) {
            self.status = WifiConnectStatusUnsubscribed;
        }
    }];
}

-(void)stopAnimation {
    [self.imageView2.layer removeAllAnimations];
    
    if (_timer && _timer.isValid) {
        [_timer invalidate];
        _timer = nil;
    }
}

#pragma mark - GizWifiDeviceDelegate
-(void)device:(GizWifiDevice *)device didSetSubscribe:(NSError *)result isSubscribed:(BOOL)isSubscribed {
    if(result.code == GIZ_SDK_SUCCESS && isSubscribed) {
        self.status = WifiConnectStatusSubscribed;
    } else {
        self.status = WifiConnectStatusUnsubscribed;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
